const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const { logOperation } = require('./logs');
const bodyParser = require('body-parser');

// 状态码定义
const CODE = {
  SUCCESS: 0,
  PARAM_ERROR: 1001,
  NOT_FOUND: 1002,
  SERVER_ERROR: 500,
  NO_PERMISSION: 1003
};

// 使用 body-parser 处理 x-www-form-urlencoded 格式
router.use(bodyParser.urlencoded({ extended: true }));

/**
 * 获取模块列表
 * GET /api/modules/list
 * 支持按项目ID筛选和分页
 */
router.get('/list', async (req, res) => {
  try {
    const {
      page = 1,
      pageSize = 10,
      projectId,
      name,
      status,
      leaderId
    } = req.query;

    let conditions = [];
    let params = [];

    // 构建查询条件
    if (projectId) {
      conditions.push('m.project_id = ?');
      params.push(projectId);
    }
    if (name) {
      conditions.push('m.name LIKE ?');
      params.push(`%${name}%`);
    }
    if (status) {
      conditions.push('m.status = ?');
      params.push(status);
    }
    if (leaderId) {
      conditions.push('m.leader_id = ?');
      params.push(leaderId);
    }

    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
    const offset = (page - 1) * pageSize;

    // 获取模块列表
    const [modules] = await pool.execute(
      `SELECT 
        m.*, 
        p.name as project_name, 
        u.username as leader_name,
        (SELECT COUNT(*) FROM tasks WHERE module_id = m.id) as task_count,
        (SELECT COUNT(*) FROM bugs WHERE module_id = m.id AND status != 'closed') as active_bug_count
       FROM modules m
       LEFT JOIN projects p ON m.project_id = p.id
       LEFT JOIN users u ON m.leader_id = u.id
       ${whereClause}
       ORDER BY m.create_time DESC
       LIMIT ? OFFSET ?`,
      [...params, parseInt(pageSize), offset]
    );

    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM modules m ${whereClause}`,
      params
    );

    res.json({
      code: CODE.SUCCESS,
      message: '获取模块列表成功',
      data: {
        total: countResult[0].total,
        list: modules,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    console.error('获取模块列表错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 创建新模块
 * POST /api/modules/add
 */
router.post('/add', async (req, res) => {
  try {
    // 处理 x-www-form-urlencoded 格式
    const {
      projectId = req.body['projectId'],
      name = req.body['name'],
      description = req.body['description'],
      status = req.body['status'] || 'pending',
      leaderId = req.body['leaderId'] ,
      startDate = req.body['startDate'],
      endDate = req.body['endDate'] 
    } = req.body;

    console.log("请求数据:",req.body);

     // 参数验证
    if (!name || !projectId) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '模块名称和项目ID不能为空'
      });
    }

    // 检查项目是否存在
    const [projects] = await pool.execute(
      'SELECT id FROM projects WHERE id = ?',
      [projectId]
    );

    if (projects.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '项目不存在'
      });
    }

    // 检查模块名是否重复
    const [existingModules] = await pool.execute(
      'SELECT id FROM modules WHERE name = ? AND project_id = ?',
      [name, projectId]
    );

    if (existingModules.length > 0) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '同一项目中模块名称已存在'
      });
    }

    // 插入模块
    const [result] = await pool.execute(
      `INSERT INTO modules 
       (project_id, name, description, status, leader_id, start_date, end_date, create_time) 
       VALUES (?, ?, ?, ?, ?, ?, ?, NOW())`,
      [
        projectId, 
        name, 
        description, 
        status, 
        leaderId, 
        startDate, 
        endDate
      ]
    );

    // 记录操作日志
    await logOperation(
      {
        userId: req.user.userId,
        type: 'create',
        module: '模块管理',
        details: `创建新模块：${name}`,
        ipAddress: req.ip,
        userAgent: req.headers['user-agent']
      }
      // req.user.userId,
      // 'create',
      // '模块管理',
      // `创建新模块：${name}`,
      // req.ip,
      // req.headers['user-agent']
    );

    res.json({
      code: CODE.SUCCESS,
      message: '创建模块成功',
      data: {
        id: result.insertId,
        name
      }
    });
  } catch (error) {
    console.error('创建模块错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 更新模块
 * PUT /api/modules/save/:id
 */
router.put('/save', async (req, res) => {
  try {
    const { id } = req.body;

    if (!id) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '模块ID不能为空'
      });
    }

    // 处理 x-www-form-urlencoded 格式
    const {
      projectId = req.body['projectId'],
      name = req.body['name'],
      description = req.body['description'],
      status = req.body['status'],
      leaderId = req.body['leaderId'] ,
      startDate = req.body['startDate'] ,
      endDate = req.body['endDate']
    } = req.body;

    // 参数验证
    if (!name) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '模块名称不能为空'
      });
    }

    // 检查模块是否存在
    const [modules] = await pool.execute(
      'SELECT * FROM modules WHERE id = ?',
      [id]
    );

    if (modules.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '模块不存在'
      });
    }

    // 如果更换项目，检查项目是否存在
    if (projectId) {
      const [projects] = await pool.execute(
        'SELECT id FROM projects WHERE id = ?',
        [projectId]
      );

      if (projects.length === 0) {
        return res.json({
          code: CODE.NOT_FOUND,
          message: '项目不存在'
        });
      }
    }

    // 更新模块
    const [result] = await pool.execute(
      `UPDATE modules 
       SET project_id = COALESCE(?, project_id), 
           name = ?, 
           description = COALESCE(?, description), 
           status = COALESCE(?, status), 
           leader_id = COALESCE(?, leader_id), 
           start_date = COALESCE(?, start_date), 
           end_date = COALESCE(?, end_date),
           update_time = NOW()
       WHERE id = ?`,
      [
        projectId, 
        name, 
        description, 
        status, 
        leaderId, 
        startDate, 
        endDate, 
        id
      ]
    );

    // 记录操作日志
    await logOperation(
      {
        userId: req.user.userId,
        type: 'update',
        module: '模块管理',
        details: `更新模块：${name}`,
        ipAddress: req.ip,
        userAgent: req.headers['user-agent']
      }
      // req.user.userId,
      // 'update',
      // '模块管理',
      // `更新模块：${name}`,
      // req.ip,
      // req.headers['user-agent']
    );

    res.json({
      code: CODE.SUCCESS,
      message: '更新模块成功'
    });
  } catch (error) {
    console.error('更新模块错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 删除模块
 * DELETE /api/modules/delete
 */
router.delete('/delete', async (req, res) => {
  const connection = await pool.getConnection();
  
  try {
    const { id } = req.query;

    if (!id) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '模块ID不能为空'
      });
    }

    // 开始事务
    await connection.beginTransaction();

    // 先删除与该模块相关的 bugs
    const [bugDeleteResult] = await connection.execute(
      'DELETE FROM bugs WHERE module_id = ?', 
      [id]
    );

    // 删除与模块相关的任务
    const [taskDeleteResult] = await connection.execute(
      'DELETE FROM tasks WHERE module_id = ?', 
      [id]
    );

    // 然后删除模块
    const [moduleDeleteResult] = await connection.execute(
      'DELETE FROM modules WHERE id = ?',
      [id]
    );

    // 提交事务
    await connection.commit();

    res.json({
      code: CODE.SUCCESS,
      message: '模块删除成功',
      data: {
        deletedBugs: bugDeleteResult.affectedRows,
        deletedTasks: taskDeleteResult.affectedRows,
        deletedModules: moduleDeleteResult.affectedRows
      }
    });
  } catch (error) {
    // 回滚事务
    await connection.rollback();
    
    console.error('删除模块错误:', error);
    res.status(500).json({ 
      code: CODE.SYSTEM_ERROR,
      message: '删除模块失败',
      error: error.message 
    });
  } finally {
    // 释放连接
    connection.release();
  }
});

/**
 * 获取模块详情
 * GET /api/modules/details
 */
router.get('/details', async (req, res) => {
  try {
    const { id } = req.query;

    console.log(id);

    if (!id) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '模块ID不能为空'
      });
    }

    // 获取模块基本信息
    const [modules] = await pool.execute(
      `SELECT 
        m.*, 
        p.name as project_name, 
        u.username as leader_name,
        u.real_name as leader_real_name
       FROM modules m
       LEFT JOIN projects p ON m.project_id = p.id
       LEFT JOIN users u ON m.leader_id = u.id
       WHERE m.id = ?`,
      [id]
    );

    if (modules.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '模块不存在'
      });
    }

    const module = modules[0];

    // 获取模块任务
    const [tasks] = await pool.execute(
      `SELECT 
        t.*, 
        u.username as assignee_name
       FROM tasks t
       LEFT JOIN users u ON t.assignee_id = u.id
       WHERE t.module_id = ?
       ORDER BY t.create_time DESC`,
      [id]
    );

    // 获取模块缺陷
    const [bugs] = await pool.execute(
      `SELECT 
        b.*, 
        u.username as reporter_name,
        u2.username as assignee_name
       FROM bugs b
       LEFT JOIN users u ON b.reporter_id = u.id
       LEFT JOIN users u2 ON b.assignee_id = u2.id
       WHERE b.module_id = ?
       ORDER BY b.create_time DESC`,
      [id]
    );

    res.json({
      code: CODE.SUCCESS,
      message: '获取模块详情成功',
      data: {
        ...module,
        tasks,
        bugs
      }
    });
  } catch (error) {
    console.error('获取模块详情错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 获取模块统计概览
 * GET /api/modules/statistics/overview
 */
router.get('/statistics/overview', async (req, res) => {
  try {
    const { 
      projectId = req.query['projectId'] || req.query['project_id'] 
    } = req.query;

    let projectCondition = '';
    let params = [];

    if (projectId) {
      projectCondition = 'WHERE project_id = ?';
      params.push(projectId);
    }

    // 模块状态统计
    const [statusStats] = await pool.execute(
      `SELECT status, COUNT(*) as count 
       FROM modules 
       ${projectCondition}
       GROUP BY status`,
      params
    );

    // 活跃模块数量
    const [activeModules] = await pool.execute(
      `SELECT COUNT(*) as count 
       FROM modules 
       WHERE status = 'active' 
       ${projectCondition ? 'AND ' + projectCondition.replace('WHERE', '') : ''}`,
      params
    );

    // 即将到期的模块
    const [upcomingDeadlines] = await pool.execute(
      `SELECT 
        id, 
        name, 
        project_id, 
        end_date 
       FROM modules 
       WHERE end_date BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY)
       ${projectCondition ? 'AND ' + projectCondition.replace('WHERE', '') : ''}
       ORDER BY end_date
       LIMIT 5`,
      params
    );

    // 最近更新的模块
    const [recentModules] = await pool.execute(
      `SELECT 
        m.*, 
        u.username as leader_name,
        p.name as project_name
       FROM modules m
       LEFT JOIN users u ON m.leader_id = u.id
       LEFT JOIN projects p ON m.project_id = p.id
       ${projectCondition}
       ORDER BY m.update_time DESC
       LIMIT 5`,
      params
    );

    res.json({
      code: CODE.SUCCESS,
      message: '获取模块统计信息成功',
      data: {
        statusStats,
        activeModuleCount: activeModules[0].count,
        upcomingDeadlines,
        recentModules
      }
    });
  } catch (error) {
    console.error('获取模块统计信息错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

module.exports = router;
